package com.ty.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ty.service.StudentService;
import com.ty.service.impl.StudentServiceImpl;
import com.ty.utils.PermissionUtils;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/student/add")
public class StudentAddServlet extends HttpServlet {
    private final StudentService studentService = new StudentServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!PermissionUtils.hasAdminPermission(request)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("\"没有操作权限\"");
            return;
        }
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String name = request.getParameter("name");
            String ageStr = request.getParameter("age");
            String majorName = request.getParameter("major");
            String phone = request.getParameter("phone");
            String studentId = request.getParameter("studentId");
            
            // 参数验证
            if (name == null || name.trim().isEmpty()) {
                throw new IllegalArgumentException("姓名不能为空");
            }
            if (ageStr == null || ageStr.trim().isEmpty()) {
                throw new IllegalArgumentException("年龄不能为空");
            }
            if (majorName == null || majorName.trim().isEmpty()) {
                throw new IllegalArgumentException("专业不能为空");
            }
            if (studentId == null || studentId.trim().isEmpty()) {
                throw new IllegalArgumentException("学号不能为空");
            }
            
            int age = Integer.parseInt(ageStr);
            
            studentService.addStudent(name, age, majorName, phone, studentId);
            out.println("添加成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("添加失败：请输入有效的数字");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("添加失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("添加失败：" + e.getMessage());
        }
    }
} 